import openpyxl
import requests
import json
from openpyxl.styles import Font, Border, Side, Alignment
import argparse
import requests
import random
import json
from hashlib import md5

def trans_by_baidu(word : str): 
    post_url='https://fanyi.baidu.com/sug'
    header={'User-Agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/96.0.4664.110 Safari/537.36'}
    data={'kw':word}
    try:
        response=requests.post(post_url, data, headers=header)        
        dic_obj=response.json()
        return dic_obj['data'][0]['v']
    except:
        return None
        
parser = argparse.ArgumentParser(description='读取文件名')
parser.add_argument('--file', type=str, help='要处理的文件名')
parser.add_argument('--word', type=str, help='要查找的单词')
args = parser.parse_args()
filename = ""
if args.file:
    filename = args.file
else:
    filename = '小学英语单词.xlsx'

if args.word:
    print(trans_by_baidu(args.word))
    exit()
    
workbook = openpyxl.load_workbook(filename)
font = Font(name='等线', size=11)
alignment = Alignment(wrap_text=True, vertical='top')
alignment2 = Alignment(wrap_text=True, vertical='center')
thin_border = Border(left=Side(style='thin'),right=Side(style='thin'),top=Side(style='thin'),bottom=Side(style='thin'))
list_words = set()

sheet = workbook.active
for row_num in range(2, 3000):
    word = sheet.cell(row_num, 4).value
    mean = sheet.cell(row_num, 1).value
    if mean and len(mean) > 0:
        continue
    print("正在处理第 %d 个单词: %s" % (row_num, word))
    if word and len(word) > 0:
        result = trans_by_baidu(word)
        if result != None:
            sheet.cell(row=row_num, column=1).value = result
        else:
            sheet.cell(row=row_num, column=1).value = ""
            print("\t\t\t\t==============>第 %d 个单词( %s )未找到含义" % (row_num, word))
        if word in list_words:
            print("\t\t\t\t==============>第 %d 个单词(%s)重复了" % (row_num, word))
        else:
            list_words.add(word)
    else:
        break
    workbook.save(filename)